import 'package:flutter/material.dart';
import 'package:flutter_chat/common/constant/constants.dart';
import 'package:flutter_chat/common/store/stores.dart';
import 'package:get/get.dart';

/// 认证中间件
class AuthRouteMiddleware extends GetMiddleware {
  // priority 数字小优先级高
  @override
  int? priority = 0;

  AuthRouteMiddleware({required this.priority});

  @override
  RouteSettings? redirect(String? route) {
    // 不需要认证的路由
    List<String> noAuthRoutes = [
      RouterName.login,
      RouterName.register,
    ];
    // 如果当前用户已经登录
    if (UserStore.to.isLogin) {
      // 如果当前路由不是首页
      if (noAuthRoutes.contains(route) && route != RouterName.index) {
        return const RouteSettings(name: RouterName.index);
      }
    } else {
      // 如果当前用户未登录
      // 如果当前路由不是白名单
      if (!noAuthRoutes.contains(route)) {
        return const RouteSettings(name: RouterName.login);
      }
    }
    return null;
  }
}
